import pymysql
from pymysql import cursors


class HtmlOutputer(object):
    def __init__(self):
        # 相当于类里面的全局变量，先存一个数据备份，供output等函数使用
        self.datas = []

    def collect_data(self, new_url, new_data):
        assert new_url is not None
        assert new_data is not None
        self.datas.append((new_url, new_data))

    def output_html(self):
        """
        输出到output.html
        :return:
        """
        file = open('output.html', mode='w')
        # 从例子可以看出django的模版渲染语言原理
        file.write("<html>")
        file.write("<body>")

        for row in self.datas:
            file.write("<tr>")
            file.write(f"<td>{row[0]}</td>")
            file.write(f"<td>{row[1]['title']}</td>")
            file.write(f"<td>{row[1]['summary']}</td>")
            file.write("</tr>")

        file.write("</body>")
        file.write("</html>")

    def save_db(self):
        connect = pymysql.connect(host="localhost", port=3306, user='root', password='0622PIG', db='test', charset='utf8mb4', cursorclass=cursors.DictCursor)
        try:
            with connect.cursor() as cursor:
                cursor.execute("""create table if not exists baike(id INT PRIMARY KEY AUTO_INCREMENT, url TEXT, title TEXT, summary TEXT);""")
                connect.commit()
            with connect.cursor() as cursor:
                for row in self.datas:
                    cursor.execute(f"""INSERT INTO baike(url,title, summary) VALUES ('{row[0]}','{row[1]['title']}','{row[1]['summary']}');""")
                connect.commit()
        except Exception as e:
            print(e)
        finally:
            connect.close()
